#include "EpollServerET.hpp"
#include "Protocol.hpp"

#include <memory>

static Response calculator(const Request &req)
{
    Response resp(0, 0);
    switch (req.op_)
    {
    case '+':
        resp.result_ = req.x_ + req.y_;
        break;
    case '-':
        resp.result_ = req.x_ - req.y_;
        break;
    case '*':
        resp.result_ = req.x_ * req.y_;
        break;
    case '/':
        if (0 == req.y_)
            resp.code_ = 1;
        else
            resp.result_ = req.x_ / req.y_;
        break;
    case '%':
        if (0 == req.y_)
            resp.code_ = 2;
        else
            resp.result_ = req.x_ % req.y_;
        break;
    default:
        resp.code_ = 3;
        break;
    }
    return resp;
}


void NetCal(FangZhang::Connection* conn, std::string& msg)
{
    // 反序列化，得到计算的元素
    Request req;
    req.Deserialized(msg);

    // 计算得到结果
    Response resp = calculator(req);

    // 将结果序列化，从而方便返回给客户端
    std::string res = resp.Serialize();
    // res即结果，进行加码
    Encode(res);
    // 加码后放到发送缓冲区中待发送
    conn->_sendBuff += res;

    // 想办法让服务端将计算的结果返回给客户端
    conn->_prsvr->EnableReadWrite(conn, true, true);
}


int main()
{
    std::unique_ptr<FangZhang::EpollServerET> svr(new FangZhang::EpollServerET());
    svr->Start(NetCal);

    return 0;
}